package com.tianhao.luo.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author tianhao.luo@hand-china.com
 */
public class SaleTicket {


    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        // 创建多个线程 调用资源类的操作方法
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "thread a").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
                try {
                    Thread.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "thread b").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "thread c").start();
    }


    /**
     * 第一步创建资源类，创建属性和操作方法
     */
    static class Ticket {
        /**
         * 票数
         */
        private int number = 30;

        /**
         * 锁
         */
        private final ReentrantLock lock = new ReentrantLock();


        /**
         * 卖票
         */
        private void sale() {
            //加锁
            lock.lock();
            try {
                if (number > 0) {
                    System.out.println(Thread.currentThread().getName() + ":卖出：" + (number--) + "还剩下：" + number);
                }
            } finally {
                // 不管是否出现异常，都会走到这里
                lock.unlock();
            }
        }
    }
}
